using System;
using System.IO;

namespace Uniriotec.DC
{

    public class VideoStream
    {

        private FileStream fis; //video file
        private int frame_nb; //current frame nb

        public int ActualFrame
        {
            get { return frame_nb; }
            set { frame_nb = value; }
        }

        //-----------------------------------
        //constructor
        //-----------------------------------
        public VideoStream(string filename)
        {

            //init variables
            fis = new FileStream(filename, FileMode.Open, FileAccess.Read);
            frame_nb = 0;
        }

        public void SkipToFrame(int frameNum)
        {
            fis.Seek(0, SeekOrigin.Begin);

            for (int i = 1; i < frameNum; i++)
            {
                SkipNextFrame();
            }

        }

        public void SkipNextFrame()
        {
            int length = 0;
            String length_string = String.Empty;
            byte[] frame_length = new byte[5];

            //read current frame length
            fis.Read(frame_length, 0, 5);

            //transform frame_length to integer
            foreach (byte value in frame_length)
                length_string += (char)value;

            length = int.Parse(length_string);

            fis.Seek(length, SeekOrigin.Current);
        }

        //-----------------------------------
        // getnextframe
        //returns the next frame as an array of byte and the size of the frame
        //-----------------------------------
        public int GetNextFrame(byte[] frame)
        {
            int length = 0;
            String length_string = String.Empty;
            byte[] frame_length = new byte[5];

            //read current frame length
            fis.Read(frame_length, 0, 5);


            //transform frame_length to integer
            foreach (byte value in frame_length)
                length_string += (char)value;

            //length_string = frame_length.GetValue//Convert.ToString(frame_length);
            length = int.Parse(length_string);

            return (fis.Read(frame, 0, length));
        }
    }
}